﻿using System;
using System.Collections.Generic;
using System.Linq;
using NFine.Code;
using NFine.Data;
using NFine.Domain._03_Entity.Biz;
using NFine.Domain._04_IRepository.Biz;
using NFine.Repository.Biz;

namespace NFine.Application.Biz
{
    public class UserPropertyApp
    {
        private IUserPropertyRepository userPropertyRepository = new UserPropertyRepository();

        public UserPropertyEntity GetMemberProperty(string id)
        {
            UserPropertyEntity userPropertyEntity = new UserPropertyEntity();
            var expression = ExtLinq.True<UserPropertyEntity>();
            expression = expression.And(a => a.F_UserId == id);
            List<UserPropertyEntity> list = userPropertyRepository.FindList(expression);
            if (list != null && list.Count >= 0)
            {
                userPropertyEntity = list[0];
            }
            return userPropertyEntity;
        }


        public bool UpdateMemberProperty(string userId, decimal money)
        {
            var expression = ExtLinq.True<UserPropertyEntity>();
            List<UserPropertyEntity> list = new List<UserPropertyEntity>();

            expression = expression.And(t => t.F_UserId == userId);
            list = userPropertyRepository.FindList(expression).ToList();

            if (list != null && list.Count > 0)
            {
                list[0].F_Property += money;
                list[0].F_LastModifyTime = DateTime.Now;
                //userPropertyRepository.Update(list[0]);
                try
                {
                    //开启事务
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        db.Update(list[0]);
                        int result = db.Commit();
                        if (result <= 0)
                            return false;
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

            return false;
        }

        public UserPropertyEntity GetUpdateMemberProperty(string userId, decimal money)
        {
            var expression = ExtLinq.True<UserPropertyEntity>();
            List<UserPropertyEntity> list = new List<UserPropertyEntity>();

            expression = expression.And(t => t.F_UserId == userId);
            list = userPropertyRepository.FindList(expression).ToList();
            if (list != null && list.Count > 0)
            {
                list[0].F_Property += money;
                list[0].F_LastModifyTime = DateTime.Now;
                return list[0];
            }

            return null;
        }

    }
}